import { Init, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Equal } from 'typeorm';
import { VisitInfoEntity } from '../entity/info';
import { UserInfoEntity } from '../../user/entity/info';

/**
 * visitInfo模块-访问信息
 */
@Provide()
export class VisitInfoService extends BaseService {
  @InjectEntityModel(VisitInfoEntity)
  visitInfoEntity: Repository<VisitInfoEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.visitInfoEntity);
  }

  /**
   * 获取用户信息
   * @param id
   * @returns
   */
  async person(id) {
    return await this.userInfoEntity.findOneBy({ id: Equal(id) });
  }

  /**
   * 更新用户信息
   * @param id
   * @param param
   * @returns
   */
  async updateVisitInfo(id, param) {
    const info = await this.person(id);
    if (!info) throw new CoolCommException('用户不存在');
    try {
      return await this.visitInfoEntity.update({ id }, param);
    } catch (err) {
      throw new CoolCommException('更新失败，参数错误或者已存在');
    }
  }
}
